package com.atguigu.gmall.product.service.impl;


import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.product.client.common.cache.GmallCache;
import com.atguigu.gmall.product.client.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ManageServiceImpl implements ManageService {
    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;
    @Autowired
    private SpuInfoMapper spuInfoMapper;
    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;

    //一级分类
    @Override
    public List<BaseCategory1> getCategory1() {
    return baseCategory1Mapper.selectList(null);
    }
    //二级分类
    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>().eq("category1_id",category1Id));
    }
    //三级分类
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>().eq("category2_id",category2Id));
    }

    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
       return baseAttrInfoMapper.selectBaseAttrInfoList(category1Id,category2Id,category3Id);
    }

    @Override
    @Transactional(rollbackFor = FileNotFoundException.class)  //默认情况 RuntimeException
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //什么情况下是添加  什么情况下是更新  修改   根据baseAttrInfo的Id
        //baseAttrInfo
        if (baseAttrInfo.getId() != null){
            //修改数据
            baseAttrInfoMapper.updateById(baseAttrInfo);
        }else{
            //添加数据
            baseAttrInfoMapper.insert(baseAttrInfo);
        }
        //baseAttrValue  平台属性值
        //修改  通过先删除baseAttrValue  在新增的方式
        //删除条件   baseAttrValue.attrId=baseAttrInfo.id
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if (attrValueList != null && attrValueList.size()>0){
            //循环遍历
            for (BaseAttrValue baseAttrValue : attrValueList) {
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(baseAttrValue);
            }
        }

    }

    @Override
    public BaseAttrInfo getAttrInfo(Long attrId) {
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);
        baseAttrInfo.setAttrValueList(getAttrValueList(attrId));
        return  baseAttrInfo;
    }

    //品牌集合 分页查询
    @Override
    public IPage baseTrademark(Integer page, Integer limit) {
        return baseTrademarkMapper.selectPage(new Page<>(page,limit),null);

    }

    //查询商品集合 分页
    @Override
    public IPage findSpuList(Integer page, Integer limit, Long category3Id) {
        QueryWrapper<SpuInfo> spuInfoQueryWrapper = new QueryWrapper<>();
        QueryWrapper<SpuInfo> category3_id = spuInfoQueryWrapper.eq("category3_id", category3Id);
        return spuInfoMapper.selectPage(new Page<>(page,limit),category3_id);
    }

    @Override
    public List<BaseTrademark> getTrademarkList() {
       return baseTrademarkMapper.selectList(new QueryWrapper<BaseTrademark>(null));
    }

    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    @Override
    @Transactional
    public void saveSpuInfo(SpuInfo spuInfo) {
            //Spuinfo商品表
        spuInfoMapper.insert(spuInfo);
            //spuImage图片表
        spuInfo.getSpuImageList().forEach(spuImage -> {
            spuImage.setSpuId(spuInfo.getId());
            spuImageMapper.insert(spuImage);
        });
        //3:销售属性表
        spuInfo.getSpuSaleAttrList().forEach(spuSaleAttr -> {
            spuSaleAttr.setSpuId(spuInfo.getId());
            spuSaleAttrMapper.insert(spuSaleAttr);
            //4:销售属性值表
            spuSaleAttr.getSpuSaleAttrValueList().forEach(spuSaleAttrValue -> {
                spuSaleAttrValue.setSpuId(spuInfo.getId());
                spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            });
        });
    }

    @Override
    public List<SpuImage> spuImageList(Long spuId) {
       return spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id",spuId));
    }

    @Override
    @Transactional
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
    }

    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        //上下架
        skuInfo.setIsSale(SkuInfo.NOSALE);
        //库存表
        skuInfoMapper.insert(skuInfo);
        //库存单元图片表
        skuInfo.getSkuImageList().forEach(skuImage -> {
            skuImage.setSkuId(skuInfo.getId());
            skuImageMapper.insert(skuImage);
        });
        //销售属性值表
        skuInfo.getSkuAttrValueList().forEach(skuAttrValue -> {
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        });
        //平台属性值的中间表
        skuInfo.getSkuSaleAttrValueList().forEach(skuSaleAttrValue -> {
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        });
    }

    @Override
    public IPage skuList(Integer page, Integer limit) {
        return skuInfoMapper.selectPage(new Page<>(page,limit),null);
    }

    @Autowired
    private RabbitService rabbitService;
    //上架
    @Override
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.ISSALE);
        skuInfoMapper.updateById(skuInfo);
        //  将来 保存数据到ES中
        rabbitService.sendMessage(
                MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_UPPER,
                skuId);

    }
    //下架
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.NOSALE);
        skuInfoMapper.updateById(skuInfo);
        // 将来 删除ES中数据
        rabbitService.sendMessage(
                MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_LOWER,
                skuId);

    }

    //1. 根据三级分类id 查询一二三级分类
    @Override
    public BaseCategoryView getBaseCategoryView(Long category3Id) {
        return  baseCategoryViewMapper.selectById(category3Id);
    }

    //分布式缓存加上了  解决缓存三大问题  同时也会加上锁
    @Autowired
    private RedissonClient redissonClient;

    //2.查询Sku中的信息 sku_info 查询sku中的图片  sku_image
    @Override
    @GmallCache(prefix = "getSkuInfo")    //@GmallCache 自定义注解  流程解决了缓存三大问题  解决了代码的冗余  哪个方法需要之间打注解即可
    public SkuInfo getSkuInfo(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (skuInfo != null){
            List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));
            skuInfo.setSkuImageList(skuImageList);
        }
        return skuInfo;
    }

    /*public SkuInfo getSkuInfo(Long skuId) {
        //查询缓存
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if (skuInfo != null){
            return skuInfo;
        }else{
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            RLock lock = redissonClient.getLock(cacheLockKey);
            //lock.lock();//不见不散  不拿到这个锁 就不会继续执行  必须要拿到这个锁才可以
            //参数1 : 过期不候  期的时间 等多久之后就不在拿锁了
            //参数2 : 拿到锁后 锁的过期时间是多少  防止死锁
            //参数3 : 时间的单位
            try {
                //过期不候  拿不到就会一直  直到能拿到为止
                boolean tryLock = lock.tryLock(1,1,TimeUnit.SECONDS);
                if (tryLock){
                    //1:skuInfo   主键
                    skuInfo = skuInfoMapper.selectById(skuId);
                    if (null != skuInfo) {
                        //2:skuImage  外键
                        List<SkuImage> skuImageList = skuImageMapper.
                                selectList(new QueryWrapper<SkuImage>()
                                        .eq("sku_id", skuId));
                        skuInfo.setSkuImageList(skuImageList);
                        //保存缓存中一份   new Random().nextInt(300)  解决雪崩问题
                        redisTemplate.opsForValue().set(cacheKey, skuInfo,
                                RedisConst.SKUKEY_TIMEOUT +
                                        new Random().nextInt(300), TimeUnit.SECONDS);
                    } else {
                        //缓存穿透
                        skuInfo = new SkuInfo();
                        //解决穿透
                        redisTemplate.opsForValue().set(cacheKey, skuInfo,
                                5, TimeUnit.MINUTES);
                    }
                }else{
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
                return skuInfo;
    }*/

    ////2.查询Sku中的信息 sku_info 查询sku中的图片  sku_image
    //@Override
    //public SkuInfo getSkuInfo(Long skuId) {
    //    //查询缓存   cacheKey缓存key
    //    String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
    //    SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
    //    if (skuInfo != null) {
    //        return skuInfo;
    //    } else {
    //        //解决缓存击穿  上分布式锁
    //        String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
    //        // 上分布式锁  设置过期时间
    //        String uuid = UUID.randomUUID().toString();
    //        Boolean isLock = redisTemplate.opsForValue().setIfAbsent(cacheLockKey, uuid, 1, TimeUnit.SECONDS);
    //        if (isLock) {
    //            skuInfo = skuInfoMapper.selectById(skuId);
    //            if (skuInfo != null) {
    //                List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));
    //                skuInfo.setSkuImageList(skuImageList);
    //                //保存缓存中一份 new Random().nextInt(300) 解决缓存雪崩
    //                redisTemplate.opsForValue().set(cacheKey, skuInfo,
    //                        RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300), TimeUnit.SECONDS);
    //                /*//删除锁   解锁   防止误删
    //                String u = (String) redisTemplate.opsForValue().get(cacheLockKey);
    //                if (uuid.equals(u)){
    //                    redisTemplate.delete(cacheLockKey);
    //                }*/
    //                //释放锁 del
    //            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
    //            this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList(cacheLockKey), uuid);
    //        } else {
    //            //解决缓存穿透
    //            skuInfo = new SkuInfo();
    //            redisTemplate.opsForValue().set(cacheKey, skuInfo, 5 * 60, TimeUnit.SECONDS);
    //        }
    //        try {
    //            TimeUnit.SECONDS.sleep(2);
    //        } catch (InterruptedException e) {
    //            e.printStackTrace();
    //        }
    //        return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
    //    }
    //}
    //        return skuInfo;
    //}

    //3. 查询价格
    @Override
    public BigDecimal getPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (skuInfo != null){
            return skuInfo.getPrice();
        }
        return new BigDecimal("0");

    }
    //4.查询spu中总销售属性 及属性值
    @Override
    public List<SpuSaleAttr> getSaleAttrAndValueAndChecked(Long skuId, Long spuId) {
        return spuSaleAttrMapper.getSaleAttrAndValueAndChecked(skuId,spuId);
    }
    //5.查询页面上 组合与skuId之间关系 {41|45 : skuId, 1|4|7 : skuId}
    @Override
    public Map<String, String> getSkuValueIdsMap(Long spuId) {
        List<Map<String, Object>> listMap= skuSaleAttrValueMapper.getSkuValueIdsMap(spuId);
        Map<String, String> result =new HashMap<>();
        listMap.forEach(map ->{
            result.put(String.valueOf(map.get("value_ids")),String.valueOf(map.get("sku_id")));
        });
        return result;
    }

    //查询所有一二三级分类视图
    @Override
    public List<BaseCategoryView> getBaseCategoryViewList() {
        return baseCategoryViewMapper.selectList(null);
    }

    //根据tmId 查询品牌列表
    @Override
    public BaseTrademark getBaseTrademark(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }
    //根据skuId查询三表关联数据  sku_attr_value base_sku_info base_attr_value
    @Override
    public List<SkuAttrValue> getSkuAttrValue(Long skuId) {
        return skuAttrValueMapper.getSkuAttrValue(skuId);
    }

    @Override
    public void saveTrademark(BaseTrademark baseTrademark) {
            baseTrademarkMapper.insert(baseTrademark);
    }

    private List<BaseAttrValue> getAttrValueList(Long attrId) {

        QueryWrapper<BaseAttrValue> baseAttrValueQueryWrapper = new QueryWrapper<>();
        baseAttrValueQueryWrapper.eq("attr_id",attrId);
        List<BaseAttrValue> baseAttrValues = baseAttrValueMapper.selectList(baseAttrValueQueryWrapper);
        return baseAttrValues;
    }

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private  SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    private RedisTemplate redisTemplate;

}
